package com.windystory.wslibrary.ui.webview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.windystory.wslibrary.base.photoShow.ShowPicActivity;
import com.windystory.wslibrary.util.LogUtil;
import com.windystory.wslibrary.util.PrefUtil;
import com.windystory.wslibrary.util.event.Event;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * JS调用原生方法
 */
public class OpenNativeMethod {
    private Context mContent;
    final static public String FilePath = Environment.getExternalStorageDirectory() + "/safeHelper";

    public OpenNativeMethod(Context mContent) {
        this.mContent = mContent;
    }

    /**
     * 关闭方法
     */
    @JavascriptInterface
    public void finish() {
        Activity activity = (Activity) mContent;
        if (activity != null)
            activity.finish();
    }


    /**
     * 拨打电话
     */
    @SuppressLint("CheckResult")
    @JavascriptInterface
    public void callPhone(final String phoneNumber) {
        Activity activity = (Activity) mContent;
        activity.runOnUiThread(() -> new RxPermissions((Activity) mContent)
                .request(Manifest.permission.CALL_PHONE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContent.startActivity(intent);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(mContent);
                            builder.setTitle("权限未打开");
                            builder.setMessage("打电话权限未开启，请在设置里面开启此权限");
                            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setAction("android.main_mine_settings.APPLICATION_DETAILS_SETTINGS");
                                    intent.setData(Uri.fromParts("package", mContent.getPackageName(), null));
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    mContent.startActivity(intent);
                                }
                            });
                            builder.show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                }));
    }


    /**
     * 显示大图
     */
    @JavascriptInterface
    public void showImages(String[] imgs, int position) {
        Activity activity = (Activity) mContent;
        if (activity != null) {
            List<String> picsList = new ArrayList<>();
            if (imgs != null) {
                for (int i = 0; i < imgs.length; i++) {
                    picsList.add(imgs[i]);
                }
                ShowPicActivity.startActivity(activity, picsList, position);
            }
        }
    }


    /**
     * 打开方法
     */
    @JavascriptInterface
    public void openAndroidActivity(String activity) {
        Intent intent = new Intent();
        ComponentName cn =
                new ComponentName(mContent.getPackageName(),
                        activity);
        intent.setAction(Intent.ACTION_MAIN);
        intent.setComponent(cn);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContent.startActivity(intent);
    }


    /**
     * 缓存字符串数据
     */
    @JavascriptInterface
    public void saveStrDataCache(String key, String data) {
        Activity activity = (Activity) mContent;
        PrefUtil.setPrefString(activity, key, data);
    }

    /**
     * 取出字符串数据
     *
     * @return 默认返回空字符串 ""
     */
    @JavascriptInterface
    public String getStrDataCache(String key) {
        Activity activity = (Activity) mContent;
        return PrefUtil.getPrefString(activity, key, "");
    }


    /**
     * 缓存int数据
     */
    @JavascriptInterface
    public void saveIntDataCache(String key, int data) {
        Activity activity = (Activity) mContent;
        PrefUtil.setPrefInt(activity, key, data);
    }

    /**
     * 取出int数据
     */
    @JavascriptInterface
    public long getIntDataCache(String key) {
        Activity activity = (Activity) mContent;
        return PrefUtil.getPrefInt(activity, key, 0);
    }


    /**
     * 缓存int数据
     */
    @JavascriptInterface
    public void saveLongDataCache(String key, long data) {
        Activity activity = (Activity) mContent;
        PrefUtil.setPrefLong(activity, key, data);
    }

    /**
     * 取出int数据
     *
     * @return 默认返回0
     */
    @JavascriptInterface
    public long getLongDataCache(String key) {
        Activity activity = (Activity) mContent;
        return PrefUtil.getPrefLong(activity, key, 0);
    }


    /**
     * 缓存float数据
     */
    @JavascriptInterface
    public void saveFloatDataCache(String key, float data) {
        Activity activity = (Activity) mContent;
        PrefUtil.setPrefFloat(activity, key, data);
    }

    /**
     * 取出float数据
     *
     * @return 默认返回0
     */
    @JavascriptInterface
    public float getFloatDataCache(String key) {
        Activity activity = (Activity) mContent;
        return PrefUtil.getPrefFloat(activity, key, 0);
    }


    /**
     * 缓存float数据
     */
    @JavascriptInterface
    public void saveBooleanDataCache(String key, boolean data) {
        Activity activity = (Activity) mContent;
        PrefUtil.setPrefBoolean(activity, key, data);
    }

    /**
     * 取出float数据
     *
     * @return 默认返回false
     */
    @JavascriptInterface
    public boolean getBooleanDataCache(String key) {
        Activity activity = (Activity) mContent;
        return PrefUtil.getPrefBoolean(activity, key, false);
    }


    /**
     * 保存文件
     * OpenNativeMethod.saveFile(URL,FILENAME);
     * -URL         下载地址
     * -FILENAME    文件名字，注意需要待拓展名
     */
    @SuppressLint("CheckResult")
    @JavascriptInterface
    public void saveFile(String URL, final String fileName) {
        LogUtil.e("下载URL--->", URL);
        LogUtil.e("fileName--->", fileName);
        final Activity activity = (Activity) mContent;
        activity.runOnUiThread(() -> new RxPermissions(activity)
                .request(Manifest.permission.CALL_PHONE)
                .subscribe(aBoolean -> {
                    final ProgressDialog dialog = new ProgressDialog(activity);
                    dialog.setMessage("下载中...");
                    if (aBoolean) {
                        dialog.show();
                        FileDownloader.setup(activity);
                        FileDownloader.getImpl().create(URL)
                                .setPath(FilePath + File.separator + fileName)
                                .setListener(new FileDownloadListener() {
                                    @Override
                                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                    }

                                    @Override
                                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                    }

                                    @Override
                                    protected void completed(BaseDownloadTask task) {
                                        dialog.dismiss();
                                        Toast.makeText(activity, "下载完成,请到safeHelper文件夹下查看", Toast.LENGTH_SHORT).show();
                                        dealFile(activity, fileName);
                                    }

                                    @Override
                                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                    }

                                    @Override
                                    protected void error(BaseDownloadTask task, Throwable e) {
                                        dialog.dismiss();
                                        Toast.makeText(activity, "下载失败", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    protected void warn(BaseDownloadTask task) {

                                    }
                                }).start();

                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContent);
                        builder.setTitle("权限未打开");
                        builder.setMessage("存储权限未开启，请在设置里面开启此权限");
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.setAction("android.main_mine_settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", mContent.getPackageName(), null));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                mContent.startActivity(intent);
                            }
                        });
                        builder.show();
                    }
                }));
    }

    /**
     * 处理png和jpg
     *
     * @param activity
     * @param fileName
     */
    public void dealFile(Activity activity, String fileName) {
        //处理png和jpg
        if (fileName.contains(".png") || fileName.contains(".jpg")) {
            File file = new File(FilePath + File.separator + fileName);
            if (!file.exists()) {
                return;
            }
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(activity.getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
                String[] paths = new String[]{file.getAbsolutePath()};
                MediaScannerConnection.scanFile(activity, paths, null, null);
            } else {
                final Intent intent;
                if (file.isDirectory()) {
                    intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                    intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
                    intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
                } else {
                    intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(file));
                }
                activity.sendBroadcast(intent);
            }
        }
    }


    /**
     * EventBus通知
     * postEvent(int eventCode)
     */
    @JavascriptInterface
    public void postEvent(int eventCode) {
        EventBus.getDefault().post(new Event(eventCode));
    }

    /**
     * EventBus通知带参数
     * postEvent(int eventCode,String params)
     */
    @JavascriptInterface
    public void postEvent(int eventCode, String params) {
        EventBus.getDefault().post(new Event(eventCode, params));
    }

    /**
     * EventBus通知带参数
     * postEvent(int eventCode,String[] params)
     */
    @JavascriptInterface
    public void postEvent(int eventCode, String[] params) {
        List<String> list = new ArrayList<>();
        if (params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                list.add(params[i]);
            }
        }
        EventBus.getDefault().post(new Event(eventCode, list));
    }


    /**
     * EventBus通知带参数
     * postEvent(int eventCode,String[] params,Object obj)
     */
    @JavascriptInterface
    public void postEvent(int what, String msg, Object obj) {
        EventBus.getDefault().post(new Event(what, msg, obj));
    }



}
